package streams;


import java.util.Random;

/**
 * Created by Tzachi on 14/10/2014.
 * <p>
 * suppose you have a stream object. This stream object ONLY has two methods. They are:
 * HasNext() - returns a boolean if there's more items in the stream
 * GetNext() - returns the next item in the stream
 * Given a stream such as this one, return a random object from it. No, the stream cannot be reset.
 */
public class GetRandomObjectFromStream {

    public int getRandomObject(Stream s) {
        int size = 1;
        int chosen = s.getNext();
        while (s.hasNext()) {
            int tmp = s.getNext();
            // random generates 0 to size - we add 1
            int random = new Random().nextInt(size) + 1;
            if (random == 1) {
                chosen = tmp;
            }
            size++;
        }
        return chosen;
    }
}
